//
//  DatabaseCache.m
//  BaiYing_Thinker
//
//  Created by 鹏 朱 on 15/10/21.
//  Copyright (c) 2015年 XKJH. All rights reserved.
//

#import "DatabaseCache.h"
#import "FMDatabaseQueue.h"
#import "FMDatabase.h"
#import "FileMangeHelper.h"
#import "SubjectMessage.h"
#import "SessonContentMessage.h"
#import "SessionMessage.h"
#import <JSONModel.h>
#import "NSDate+Addition.h"
#import "AppDelegate.h"

#define CREATE_SQL @"\
CREATE TABLE IF NOT EXISTS t_subject(subject_id VARCHAR PRIMARY KEY  NOT NULL, content VARCHAR,publishtime VARCHAR,subjecttype VARCHAR,contenttype VARCHAR);\
CREATE TABLE IF NOT EXISTS t_session(subject_id VARCHAR,session_id VARCHAR, update_time VARCHAR,primary key (subject_id,session_id));\
CREATE TABLE IF NOT EXISTS t_session_content(session_content_id INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL,msg_id VARCHAR, session_id VARCHAR,subject_id VARCHAR,subject_content VARCHAR, msg_type VARCHAR,msg_content VARCHAR,sender VARCHAR,recevier VARCHAR,create_time VARCHAR,model VARCHAR,sys_code VARCHAR,rel VARCHAR,lbskm VARCHAR,isMyself INTEGER,content_width VARCHAR,content_height VARCHAR,content_timestamp VARCHAR,content_url VARCHAR,local_Path VARCHAR,componentName VARCHAR,componentUrl VARCHAR,componentRule VARCHAR);"

@implementation DatabaseCache

+ (instancetype)shareInstance
{
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[[self class] alloc] init];
    });
    return instance;
}

- (id)init
{
    if (self = [super init])
    {
        self.m_dbPath = [self getDbPath];
    }
    return self;
}

- (BOOL)createDBWithPath:(NSString *)path
{
    if(!IsEmpty(path)) {
        self.m_dbPath = path;
        self.db = [FMDatabase databaseWithPath:self.m_dbPath];
        self.dbQueue = [FMDatabaseQueue databaseQueueWithPath:self.m_dbPath];
        if (self.dbQueue) {
            
            NSArray * parts = [CREATE_SQL componentsSeparatedByString:@";"];
            for(NSString *str in parts)
            {
                if (!IsEmpty(str)) {
                    [self.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
                        [db executeUpdate:str];
                    }];
                }
            }
        } else {
            return NO;
        }
    } else {
        return NO;
    }
    
    return YES;
}

- (NSString *)getDbPath
{    
    return [[FileMangeHelper shareInstance] getDataBasePath];
}

#pragma mark -  根据表名往表中插入一条记录
- (BOOL)InsertIntoTableFieldDict:(NSDictionary*)dic tableName:(NSString*)name
{
    if([self NSStringIsNULL:name]) return NO;
    if(dic==nil || [dic count]==0) return NO;
    
    NSArray * arrKeys=[dic allKeys];
    NSArray * arrValues=[dic allValues];
    NSUInteger count=[arrKeys count];
    NSString *sql = [NSString stringWithFormat:@"insert or ignore into %@(",name];
    NSMutableString * tempsql=[NSMutableString stringWithString:sql];
    for (int i=0; i<count; i++)
    {
        [tempsql appendString:[arrKeys objectAtIndex:i]];
        if(i != count-1)
        {
            [tempsql appendString:@","];
        }
    }
    [tempsql appendString:@") values("];
    
    for(int k=0; k<count; k++)
    {
        [tempsql appendString:@"?"];
        if(k != count-1)
        {
            [tempsql appendString:@","];
        }
    }
    [tempsql appendString:@")"];
    
    [self.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        [db executeUpdate:tempsql withArgumentsInArray:arrValues];
    }];
    
    return YES;
}

#pragma mark - 查询某个表的所有记录
- (NSMutableArray *)SelectAllByTableName:(NSString*)name
{
    NSMutableArray *list = [[NSMutableArray alloc] init];

    [self.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        NSString *sql = [NSString stringWithFormat:@"select * from %@",name];
        
        FMResultSet *rs = [db executeQuery:sql];
        while ([rs next]) {
            
            @autoreleasepool {
                NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
                for (int i =0 ; i < rs.columnCount; i++) {
                    if ([rs stringForColumnIndex:i]) {
                        
                        NSString *value = [rs stringForColumnIndex:i];
                        NSString *result = value;
                        
                        //去掉html标签，只取内容
                        if ([[rs columnNameForIndex:i] isEqualToString:@"msg_content"] && [value containsString:@"<div"] && [value containsString:@"</div>"]) {
                            
                            NSRange find = [value rangeOfString:@">"];
                            result = [value substringFromIndex:find.location + 1];
                            
                            find = [value rangeOfString:@"</div>"];
                            result = [result substringToIndex:find.location - 1];
                        }
                        
                        [dic setObject:result forKey:[rs columnNameForIndex:i]];
                        
                    } else {
                        [dic setObject:@"" forKey:[rs columnNameForIndex:i]];
                    }
                }
                [list addObject:dic];
            }
        }
    }];
    
    return list;
}

#pragma mark - 查询某个表的满足所有and条件的记录
- (NSMutableArray *)SelectAllBycondition:(NSDictionary*)dicCondtion TableName:(NSString*)name orderName:(NSArray *)orderNameList subjectContent:(NSString *)subjectContent
{
    NSMutableArray *list = [[NSMutableArray alloc] init];
    if(dicCondtion==nil || [dicCondtion count]==0) return list;

    NSArray * arrKeys=[dicCondtion allKeys];
    NSArray * arrValues=[dicCondtion allValues];
    NSUInteger count=[arrKeys count];
    
    NSString *sql = [NSString stringWithFormat:@"select * from %@ where ",name];
    
    NSMutableString * tempsql=[NSMutableString stringWithString:sql];
    for (int i=0; i<count; i++) {
        [tempsql appendString:[arrKeys objectAtIndex:i]];
        [tempsql appendString:@"=? "];
        if(i!=count-1)
        {
            [tempsql appendString:@"and "];
        }
    }
    
    if (orderNameList && orderNameList.count > 0) {
        for (int j = 0; j<orderNameList.count; j++) {
            if (j == 0) {
                [tempsql appendString:[NSString stringWithFormat:@" order by %@",orderNameList[j]]];
            } else {
                [tempsql appendString:[NSString stringWithFormat:@" ,%@",orderNameList[j]]];
            }
        }
    }
    
    [self.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        FMResultSet *rs = [db executeQuery:tempsql withArgumentsInArray:arrValues];
        while ([rs next]) {
            
            @autoreleasepool {
                NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
                for (int i =0 ; i < rs.columnCount; i++) {
                    if ([rs stringForColumnIndex:i]) {
                        
                        NSString *value = [rs stringForColumnIndex:i];
                        NSString *key = [rs columnNameForIndex:i];
                        NSString *result = [Util removeDivHtmlWithKey:key value:value];
                        
                        [dic setObject:result forKey:key];
                        
                    } else {
                        [dic setObject:@"" forKey:[rs columnNameForIndex:i]];
                    }
                }
                
                if (!IsEmpty(subjectContent)) {
                    [dic setObject:subjectContent forKey:@"subject_content"];
                }
                
                [list addObject:dic];
            }
        }
    }];

    return list;
}

#pragma mark - 删除某个表的所有记录
- (BOOL)DeleteAllByTableName:(NSString*)name
{
    [self.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        NSString *sql = [NSString stringWithFormat:@"delete from %@",name];
        [db executeUpdate:sql];
    }];
    return YES;
}

#pragma mark - 删除满足所有and条件的记录
- (BOOL)DeleteBycondition:(NSDictionary*)dicCondtion tableName:(NSString*)name
{
    if([self NSStringIsNULL:name]) return NO;
    if(dicCondtion==nil || [dicCondtion count]==0) return NO;
    
    NSArray * arrKeys=[dicCondtion allKeys];
    NSArray * arrValues=[dicCondtion allValues];
    NSUInteger count=[arrKeys count];
    NSString *sql = [NSString stringWithFormat:@"delete from %@ where ",name];
    NSMutableString * tempsql=[NSMutableString stringWithString:sql];
    for (int i=0; i<count; i++)
    {
        [tempsql appendString:[arrKeys objectAtIndex:i]];
        [tempsql appendString:@"=? "];
        if(i!=count-1)
        {
            [tempsql appendString:@"and "];
        }
    }
    [self.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        [db executeUpdate:tempsql withArgumentsInArray:arrValues];
    }];
    return YES;
}

#pragma mark - 更新满足所有条件的记录
-(BOOL)UpdateTableField:(NSDictionary*)dic condition:(NSDictionary*)dicCondtion tableName:(NSString*)name
{
    if([self NSStringIsNULL:name]) return NO;
    if(dicCondtion==nil || [dicCondtion count]==0) return NO;
    NSUInteger count=[dic count];
    if(dic==nil || count==0) return NO;
    NSArray * keyArray=[dic allKeys];
    NSString *sql = [NSString stringWithFormat:@"update %@ set ",name];
    NSMutableString * tempsql=[NSMutableString stringWithString:sql];
    
    for (int i=0; i<count; i++) {
        [tempsql appendString:[keyArray objectAtIndex:i]];
        [tempsql appendString:@"=?"];
        if(i != count-1)
        {
            [tempsql appendString:@", "];
        }
    }
    count=[dicCondtion count];
    [tempsql appendString:@" where "];
    keyArray=[dicCondtion allKeys];
    for (int i=0; i<count; i++) {
        [tempsql appendString:[keyArray objectAtIndex:i]];
        [tempsql appendString:@"=?"];
        if(i != count-1)
        {
            [tempsql appendString:@" and "];
        }
    }
    
    NSMutableArray * valArray=[NSMutableArray arrayWithArray:[dic allValues]];
    NSArray *conditionValArray=[dicCondtion allValues];
    for(int i=0;i<[conditionValArray count];i++)
    {
        [valArray addObject:[conditionValArray objectAtIndex:i]];
    }
    
    [self.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        [db executeUpdate:tempsql withArgumentsInArray:valArray];
    }];
    
    return YES;
}

- (BOOL)NSStringIsNULL:(NSString *)aStirng
{
    if(aStirng == nil) return YES;
    if ([aStirng length] == 0) return YES;
    if ([aStirng isKindOfClass:[NSNull class]])return YES;
    return NO;
}

@end

@implementation DatabaseCache(xx_message)

- (SessonContentMessage *)createSessonContentMessageWithDictionary:(NSDictionary *)subjectDic {
    
    if (subjectDic[@"contenttype"] && [subjectDic[@"contenttype"] integerValue] == 100) {
        
        SessonContentMessage *message = [[SessonContentMessage alloc] init];
        message.subject_id = subjectDic[@"subject_id"];
        message.session_id = kLocalSessionId;
        message.msg_content = subjectDic[@"content"];
        message.model = subjectDic[@"subjecttype"];
        message.msg_id = subjectDic[@"subject_id"];
        message.create_time = [NSDate currentDateStringWithFormat:@"yyyy-MM-dd mm:HH:ss"];
        
        return message;
    }
    
    return nil;
}

- (NSMutableArray *)selectSubjectInfo {
    
    NSMutableArray *infoList = [self SelectAllByTableName:KTableNameOfSubject];
    
    if (infoList && infoList.count > 0) {
        return [SubjectMessage arrayOfModelsFromDictionaries:infoList];
    }
    
    return nil;
}

- (NSMutableArray *)selectSessionInfo {

    NSMutableArray *infoList = [self SelectAllByTableName:KTableNameOfSession];
    
    if (infoList && infoList.count > 0) {
        return [SessionMessage arrayOfModelsFromDictionaries:infoList];
    }
    
    return nil;

}

- (NSMutableArray *)selectSessionContentInfo {
    
    NSMutableArray *infoList = [self SelectAllByTableName:KTableNameOfSessionContent];
    
    if (infoList && infoList.count > 0) {
        return [SessonContentMessage arrayOfModelsFromDictionaries:infoList];
    } else {
        return [[NSMutableArray alloc] init];
    }
}

- (NSMutableArray *)selectDataSource {
    
    NSMutableArray *subjectList = [self SelectAllByTableName:KTableNameOfSubject];
    NSMutableArray *returnSubjectList = [[NSMutableArray alloc] init];
    kAppDelegate.subjectList = [SubjectMessage arrayOfModelsFromDictionaries:subjectList];
    
    NSMutableArray *sessionList = [self SelectAllByTableName:KTableNameOfSession];
    kAppDelegate.sessionList = [SessionMessage arrayOfModelsFromDictionaries:sessionList];
    
    for (NSDictionary *subjectDic in subjectList) {
        
        if (subjectDic[@"subject_id"]) {
            
            NSMutableArray *sessionList = [self SelectAllBycondition:[NSDictionary dictionaryWithObjectsAndKeys:subjectDic[@"subject_id"],@"subject_id", nil] TableName:KTableNameOfSession orderName:[NSArray arrayWithObjects:@"update_time", nil] subjectContent:nil];
            
            NSMutableArray *returnSessionList = [[NSMutableArray alloc] init];
            
            for (NSDictionary *sessiontDic in sessionList) {
                
                if (sessiontDic[@"session_id"]) {
                    
                    NSMutableArray *sessionContentList = [self SelectAllBycondition:[NSDictionary dictionaryWithObjectsAndKeys:subjectDic[@"subject_id"],@"subject_id",sessiontDic[@"session_id"],@"session_id", nil] TableName:KTableNameOfSessionContent orderName:nil subjectContent:subjectDic[@"content"]];
                    
                    if (sessionContentList.count > 0) {
                        [returnSessionList addObject:[SessonContentMessage arrayOfModelsFromDictionaries:sessionContentList]];
                    }
                }
            }
            
            if (returnSessionList.count > 0) {
                [returnSubjectList addObject:returnSessionList];
            }
        }
    }
    
    kAppDelegate.sessionContentList = returnSubjectList;

    return returnSubjectList;
}

- (void)addSubjectInfo:(SubjectMessage *)info{
    
    [self InsertIntoTableFieldDict:[info toDictionary] tableName:KTableNameOfSubject];
}

- (void)addSessionInfo:(SessionMessage *)info{
        
    [self InsertIntoTableFieldDict:[info toDictionary] tableName:KTableNameOfSession];
}

- (void)addSessionContentInfo:(SessonContentMessage *)info{
    
    info.msg_content = [Util removeDivHtmlWithKey:@"msg_content" value:info.msg_content];
    SessionMessage *sessionMessage = [[SessionMessage alloc] init];
    sessionMessage.session_id = info.session_id;
    sessionMessage.subject_id = info.subject_id;
    sessionMessage.update_time = info.create_time;

    SubjectMessage *subjectMessage = [[SubjectMessage alloc] init];
    subjectMessage.subject_id = info.subject_id;
    subjectMessage.content = info.subject_content;
    subjectMessage.publishtime = info.create_time;
    subjectMessage.contenttype = info.msg_type;

    [self InsertIntoTableFieldDict:[subjectMessage toDictionary] tableName:KTableNameOfSubject];
    [self InsertIntoTableFieldDict:[sessionMessage toDictionary] tableName:KTableNameOfSession];
    
    if (IsEmpty(info.local_Path)) {
        
        [self InsertIntoTableFieldDict:[info toDictionary] tableName:KTableNameOfSessionContent];
        
    } else {
        
        NSMutableArray *list = [self SelectAllBycondition:[NSDictionary dictionaryWithObjectsAndKeys:info.subject_id,@"subject_id",info.session_id,@"session_id",info.local_Path,@"local_Path", nil] TableName:KTableNameOfSessionContent orderName:nil subjectContent:nil];
        if (list && list.count > 0) {
            
            [self UpdateTableField:[NSDictionary dictionaryWithObjectsAndKeys:info.msg_type,@"msg_type",info.content_url,@"content_url", nil] condition:[NSDictionary dictionaryWithObjectsAndKeys:info.subject_id,@"subject_id",info.session_id,@"session_id",info.local_Path,@"local_Path", nil] tableName:KTableNameOfSessionContent];
            
        } else {
            [self InsertIntoTableFieldDict:[info toDictionary] tableName:KTableNameOfSessionContent];
        }
    }
}

@end

